package cn.tedu.csmall.sso.config;

import cn.tedu.csmall.sso.filter.JwtAuthorizationFilter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@Slf4j
@EnableGlobalMethodSecurity(prePostEnabled = true) //开启全局的授权访问检查
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtAuthorizationFilter jwtAuthorizationFilter;

    @Bean
    public PasswordEncoder passwordEncoder() {
        log.info("创建密码编码器：BCryptPasswordEncoder");
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //禁用跨站请求伪造保护的配置，如果没有这个配置，白名单的异步访问也会出现403
        http.csrf().disable();
        //配置路径，暂时使用*来进行匹配
        //配置白名单，放行不需要登陆也能访问的资源
        String urls[] = {
                "/admins/login",
                "/doc.html",
                "/**/*.css",
                "/**/*.js",
                "/favicon.ico",
                "/swagger-resources",
                "/v2/api-docs"
        };
        http.authorizeRequests()//请求需要被授权才可以访问
                .antMatchers(urls)//匹配路径，/**意味着所有路径
                .permitAll()//允许直接访问（不需要经过认证和授权）
                .anyRequest()//任何请求，除了上面配置的请求
                .authenticated();//通过认证才能访问

        //添加处理JWT的过滤器，必须执行在处理用户名和密码的过滤器之前
        http.addFilterBefore(jwtAuthorizationFilter, UsernamePasswordAuthenticationFilter.class);
    }

    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }


}
